package cn.iocoder.yudao.module.book.controller.app.bookcase;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.book.controller.app.bookcase.vo.AppBooksRespVO;
import cn.iocoder.yudao.module.book.controller.app.bookcase.vo.AppBookshelfRespVO;
import cn.iocoder.yudao.module.book.service.books.BooksService;
import cn.iocoder.yudao.module.book.service.bookshelf.BookshelfService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 APP - 绘本")
@RestController
@RequestMapping("/api/user/book")
public class AppBookshelfController {

    @Resource
    private BooksService booksService;

    @Resource
    private BookshelfService bookshelfService;

    @Resource
    private cn.iocoder.yudao.module.book.service.collect.CollectService collectService;

    @Resource
    private cn.iocoder.yudao.module.book.service.users.userDTOService userService;

//    @GetMapping("/list")
//    @Operation(summary = "获得用户绘本列表")
//    public CommonResult<List<AppBooksRespVO>> list(@Valid @RequestParam("userId") Integer userId, @Valid @RequestParam("sort") String sort) {
//        List<AppBookshelfRespVO> list=bookshelfService.getAll(userId);
//        List<AppBooksRespVO> books = list.stream()
//                .map(bookshelf -> booksService.getByBookId(bookshelf.getBookId(), sort)) // 假设 getById 接受 Integer 类型的 sort 参数
//                .collect(Collectors.toList());
//
//        // 如果 sort 不是 "default"，则按绘本名称首字母排序
//        if (!"default".equalsIgnoreCase(sort)) {
//            books.sort(Comparator.comparing(book -> book.getTitle().substring(0, 1)));
//        }
//
//        return success(BeanUtils.toBean(books, AppBooksRespVO.class));
//    }

    @GetMapping("/list")
    @Operation(summary = "获得用户绘本集")
    public CommonResult<List<AppBooksRespVO>> list(@Valid @RequestParam("setId") Integer setId, @Valid @RequestParam("sort") String sort) {
        // 获取用户的所有绘本集ID
//        List<Integer> collectionIds = bookshelfService.getByCollectionId(userId).stream()
//                .map(AppBooksRespVO::getCollectionId)
//                .collect(Collectors.toList());

        // 使用 flatMap 将多个 List<AppBooksRespVO> 合并成一个 List<AppBooksRespVO>
//        List<AppBooksRespVO> books = collectionIds.stream()
//                .map(collectionId -> booksService.getByCollectionId(collectionId))
//                .filter(Objects::nonNull)
//                .flatMap(List::stream) // 展开嵌套的列表
//                .collect(Collectors.toList());

        List<AppBooksRespVO> books = bookshelfService.getdraftByCollectionId(setId);
        // 为响应列表中的每条记录附加 isCollected（按当前 setId 判断）
        try {
            Long uid = userService.getCurrentUserId();
            boolean collected = collectService.existsCollection(setId, uid);
            if (books != null) {
                for (AppBooksRespVO b : books) {
                    b.setIsCollected(collected);
                }
            }
        } catch (Exception ignore) {}

        // 如果 sort 不是 "default"，则按绘本名称排序
        if (!"default".equalsIgnoreCase(sort)) {
            books.sort(Comparator.comparing(AppBooksRespVO::getTitle));
        }
        return success(books);

    }

    @GetMapping("/removeFromSet")
    @Operation(summary = "从书架中移除绘本")
    public Boolean removeFromSet(@Valid @RequestParam("userId") Long userId, @Valid @RequestParam("bookId") Integer bookId) {
        return bookshelfService.deletes(userId,bookId);
    }
}
